const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const CopyWebpackPlugin = require('copy-webpack-plugin')

module.exports = {
  mode: "development",
  // 入口文件
  entry: path.resolve(__dirname, './src/index.ts'),
  // 出口文件 ./dist/bundle.js
  output: {
    path: path.resolve(__dirname, './dist'),
    filename: 'bundle.js',
    // 为了兼容低版本浏览器 让webpack打包不要用箭头函数 不用const
    environment: {
      arrowFunction: false,
      const: false
    }
  },
  module: {
    rules: [
      {
        // 所有ts文件用 ts-loader babel-loader依次加载(从下往上执行)
        test: /\.ts$/,
        use: [
          {
            loader: 'babel-loader',
            // babel配置(或者写到.babel里) 无论用的是es多少 通过babel转换都能兼容到需要的浏览器
            options: {
              presets: [
                [
                  '@babel/preset-env',
                  {
                    // 'targets': '> 0.25%, not dead',
                    'targets': {
                      'chrome': '80',
                      'ie': '11'
                    },
                    'corejs': '3',
                    'useBuiltIns': 'usage'
                  }
                ]
              ]
            }
          },
          // 通过tsconfig.json检查
          'ts-loader'
        ],
        exclude: /node-modules/
      },
      {
        test: /\.less$/,
        use: [
          "style-loader",
          "css-loader",
          // 引入postcss 处理css兼容性(比如加webkit-等)
          {
            loader: "postcss-loader",
            options: {
              postcssOptions: {
                plugins: [
                  "postcss-preset-env"
                ]
              }
            }
          },
          "less-loader"
        ],
        exclude: /node-modules/
      }
    ]
  },
  plugins: [
    // 模板./src/index.html自动加上出口文件./dist/bundle.js
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, './src/index.html'),
    }),
    // build后先清除再生成dist文件夹
    new CleanWebpackPlugin(),
    new CopyWebpackPlugin(
      {
        patterns: [
          { 
            from: path.resolve(__dirname, './lib/globalTitle.js'), 
            to: path.resolve(__dirname, './dist')
         },
        ],
      }
    ),
  ],
  resolve: {
    // ts里不能import './mm.ts'，只能import './mm'，配置这里后就可以import './mm.ts'了
    extensions: ['.ts', '.js']
  }
}